package com.poizon.infrastructure.lock.core.annoations.config;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.alibaba.fastjson.JSON;
import com.poizon.infrastructure.lock.core.annoations.aop.LockAspect;
import com.poizon.infrastructure.lock.core.enums.LockConstants;
import com.poizon.infrastructure.lock.core.util.ILock;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Bean;

import java.util.Map;

@Slf4j
public class AopConfig {
    @Bean
    public LockAspect lockAspect() {
        log.info(">准备初始化分布锁AOP");
        try {
            Map<String, ILock> beansOfType = SpringUtil.getBeansOfType(ILock.class);
            log.info(">获取到分布式锁实现类={}", JSON.toJSONString(beansOfType, true));

            Assert.notNull(LockConstants.lockDbTypeEnum);
            Assert.notNull(beansOfType);
            Assert.isTrue(beansOfType.values().size() != 0);

            ILock iLock = beansOfType.get(LockConstants.lockDbTypeEnum);
            Assert.notNull(iLock);

            log.info(">初始化锁注解AOP");
            return new LockAspect(iLock);
        } catch (Exception e) {
            log.error(StrUtil.format(">未定义分布式锁实现"), e);
        }
        return null;
    }
}
